package servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet 被调用...");

        //获取到用户名密码
        //123456就可以通过
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //获取session，验证合法性
        HttpSession session = req.getSession();
        Object object = session.getAttribute("username");
        if ("123456".equals(password)) {
            //合法，将用户名加入session
            req.getSession().setAttribute("username", username);
            //请求转发到管理页面
            req.getRequestDispatcher("/manage/manage.jsp")
                    .forward(req, resp);
        } else {
            //不合法，返回登录页面
            req.getRequestDispatcher("/login.jsp")
                    .forward(req, resp);
        }
    }
}
